# SIP服务启动问题诊断脚本
Write-Host "=== SIP服务启动问题诊断 ===" -ForegroundColor Green

# 1. 检查当前机器的IP地址
Write-Host "`n1. 检查当前机器的IP地址..." -ForegroundColor Yellow
try {
    $networkAdapters = Get-NetIPAddress -AddressFamily IPv4 | Where-Object { $_.IPAddress -ne "127.0.0.1" -and $_.PrefixOrigin -eq "Dhcp" -or $_.PrefixOrigin -eq "Manual" }
    Write-Host "  可用的IP地址：" -ForegroundColor White
    foreach ($adapter in $networkAdapters) {
        $adapterInfo = Get-NetAdapter -InterfaceIndex $adapter.InterfaceIndex
        Write-Host "    $($adapter.IPAddress) - $($adapterInfo.Name)" -ForegroundColor Green
    }
    
    # 检查配置中的IP是否存在
    $configIP = "172.16.235.211"
    $ipExists = $networkAdapters | Where-Object { $_.IPAddress -eq $configIP }
    if ($ipExists) {
        Write-Host "  ✓ 配置的IP地址 $configIP 存在于当前机器" -ForegroundColor Green
    } else {
        Write-Host "  ❌ 配置的IP地址 $configIP 不存在于当前机器" -ForegroundColor Red
        Write-Host "    建议使用上述可用IP地址之一" -ForegroundColor Yellow
    }
} catch {
    Write-Host "  检查IP地址时出错: $($_.Exception.Message)" -ForegroundColor Red
}

# 2. 检查端口5060是否被占用
Write-Host "`n2. 检查端口5060是否被占用..." -ForegroundColor Yellow
try {
    $port5060 = netstat -an | findstr ":5060"
    if ($port5060) {
        Write-Host "  ❌ 端口5060已被占用：" -ForegroundColor Red
        $port5060 | ForEach-Object { Write-Host "    $_" -ForegroundColor White }
        
        # 尝试找到占用端口的进程
        $processes = netstat -ano | findstr ":5060"
        if ($processes) {
            Write-Host "  占用端口的进程：" -ForegroundColor Yellow
            $processes | ForEach-Object {
                $parts = $_ -split '\s+'
                if ($parts.Length -ge 5) {
                    $pid = $parts[-1]
                    try {
                        $process = Get-Process -Id $pid -ErrorAction SilentlyContinue
                        if ($process) {
                            Write-Host "    PID: $pid - $($process.ProcessName)" -ForegroundColor White
                        }
                    } catch {
                        Write-Host "    PID: $pid - 无法获取进程信息" -ForegroundColor Gray
                    }
                }
            }
        }
    } else {
        Write-Host "  ✓ 端口5060未被占用" -ForegroundColor Green
    }
} catch {
    Write-Host "  检查端口时出错: $($_.Exception.Message)" -ForegroundColor Red
}

# 3. 检查防火墙设置
Write-Host "`n3. 检查Windows防火墙..." -ForegroundColor Yellow
try {
    $firewallProfile = Get-NetFirewallProfile -Profile Domain,Public,Private
    foreach ($profile in $firewallProfile) {
        $status = if($profile.Enabled){"启用"}else{"禁用"}
        $color = if($profile.Enabled){"Red"}else{"Green"}
        Write-Host "  $($profile.Name) 配置文件: $status" -ForegroundColor $color
    }
    
    # 检查5060端口的防火墙规则
    $firewallRules = Get-NetFirewallRule | Where-Object { $_.DisplayName -like "*5060*" -or $_.DisplayName -like "*SIP*" }
    if ($firewallRules) {
        Write-Host "  发现SIP相关防火墙规则：" -ForegroundColor Yellow
        foreach ($rule in $firewallRules) {
            Write-Host "    $($rule.DisplayName) - $($rule.Action)" -ForegroundColor White
        }
    } else {
        Write-Host "  未发现SIP相关防火墙规则" -ForegroundColor Yellow
    }
} catch {
    Write-Host "  检查防火墙时出错: $($_.Exception.Message)" -ForegroundColor Red
}

# 4. 测试端口绑定
Write-Host "`n4. 测试端口绑定..." -ForegroundColor Yellow
try {
    # 获取第一个可用的IP地址
    $availableIP = (Get-NetIPAddress -AddressFamily IPv4 | Where-Object { $_.IPAddress -ne "127.0.0.1" -and $_.PrefixOrigin -eq "Dhcp" -or $_.PrefixOrigin -eq "Manual" } | Select-Object -First 1).IPAddress
    
    if ($availableIP) {
        Write-Host "  尝试在 $availableIP:5060 绑定端口..." -ForegroundColor White
        
        # 创建简单的端口测试
        $testScript = @"
import java.net.*;
import java.io.*;

public class TestPortBinding {
    public static void main(String[] args) {
        String[] ips = {"0.0.0.0", "127.0.0.1", "$availableIP", "172.16.235.211"};
        int port = 5060;
        
        for (String ip : ips) {
            try {
                ServerSocket socket = new ServerSocket();
                socket.bind(new InetSocketAddress(ip, port));
                System.out.println("✓ 成功绑定 " + ip + ":" + port);
                socket.close();
            } catch (Exception e) {
                System.out.println("❌ 无法绑定 " + ip + ":" + port + " - " + e.getMessage());
            }
        }
    }
}
"@
        $testScript | Out-File -FilePath "TestPortBinding.java" -Encoding UTF8
        Write-Host "  ✓ 已创建端口绑定测试文件: TestPortBinding.java" -ForegroundColor Green
    }
} catch {
    Write-Host "  测试端口绑定时出错: $($_.Exception.Message)" -ForegroundColor Red
}

Write-Host "`n=== 解决方案 ===" -ForegroundColor Cyan

Write-Host "`n问题1: IP地址不正确" -ForegroundColor Yellow
Write-Host "解决方案: 修改application.yml中的SIP IP配置" -ForegroundColor White
Write-Host "  建议使用: 0.0.0.0 (监听所有网卡)" -ForegroundColor Green
Write-Host "  或使用当前机器的实际IP地址" -ForegroundColor Green

Write-Host "`n问题2: 端口被占用" -ForegroundColor Yellow
Write-Host "解决方案: 更换SIP端口或停止占用进程" -ForegroundColor White
Write-Host "  建议端口: 5061, 5062, 8116 等" -ForegroundColor Green

Write-Host "`n问题3: 防火墙阻止" -ForegroundColor Yellow
Write-Host "解决方案: 添加防火墙例外或临时禁用防火墙测试" -ForegroundColor White

Write-Host "`n推荐的application.yml配置修改：" -ForegroundColor Green
Write-Host @"
sip:
  # 使用0.0.0.0监听所有网卡，或使用实际IP地址
  ip: 0.0.0.0
  # 如果5060被占用，可以改为其他端口
  port: 8116
"@ -ForegroundColor White

Write-Host "`n下一步操作：" -ForegroundColor Green
Write-Host "1. 运行端口绑定测试: javac TestPortBinding.java && java TestPortBinding" -ForegroundColor White
Write-Host "2. 根据测试结果修改application.yml配置" -ForegroundColor White
Write-Host "3. 重新启动WVP应用程序" -ForegroundColor White

Read-Host "`n按回车键退出"
